package com.suhe.ozon.http;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.ImmutableMap;
import com.suhe.ozon.consts.OzonConsts;
import com.suhe.ozon.entity.po.ClientPO;
import com.suhe.ozon.entity.po.ProductPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * </p>
 *
 * @author liuning
 * @date 21:41 2024/1/20
 */
@Slf4j
public class ProductHttp {

    /**
     * 商品列表url
     */
    private final static String GET_PRODUCT_LIST_URL = "https://api-seller.ozon.ru/v2/product/list";

    /**
     * 商品详情url
     */
    private final static String GET_PRODUCT_INFO_URL = "https://api-seller.ozon.ru/v2/product/info";

     public void sync(ClientPO ozonClient, int page, List<ProductPO> productList) throws IOException {
         final CloseableHttpClient httpClient = HttpClients.createDefault();
         final HttpPost httpPost = new HttpPost(GET_PRODUCT_LIST_URL);
         httpPost.addHeader("Client-Id", ozonClient.getClientId());
         httpPost.addHeader("Api-Key", ozonClient.getSecretKey());
         httpPost.addHeader("Content-Type", "application/json");
         httpPost.addHeader("Host", "api-seller.ozon.ru");
         final ImmutableMap<String, Object> params = ImmutableMap.of("dir", "ASC"
                 , "filter",
                 Collections.emptyMap()
//                 ImmutableMap.of("visibility", "ALL") // 除了已归档以外的所有商品
                 , "offset", page
                 , "limit", OzonConsts.HTTP_PAGE_LIMIT
         );
         StringEntity stringEntity = new StringEntity(JSONUtil.toJsonStr(params));
         stringEntity.setContentEncoding("UTF-8");
         stringEntity.setContentType("application/json");
         httpPost.setEntity(stringEntity);

         final CloseableHttpResponse response = httpClient.execute(httpPost);
         if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
             log.error("接口请求失败");
         }
         String result = EntityUtils.toString(response.getEntity());
         final JSONObject jsonObject = JSONUtil.parseObj(result).getJSONObject("result");
         final JSONArray products = jsonObject.getJSONArray("items");
         products.parallelStream().forEach(product -> {
             final JSONObject value = (JSONObject) product;
             final String offerId = value.getStr("offer_id");
             final String productId = value.getStr("product_id");
             try {
                 productList.add(getRemoteProduct(ozonClient, productId, offerId));
             } catch (IOException e) {
                 log.error("同步商品信息失败", e);
             }
         });
         if ((page + 1) * OzonConsts.HTTP_PAGE_LIMIT < jsonObject.getInt("total")) {
             sync(ozonClient, ++page, productList);
         }
     }

     private ProductPO getRemoteProduct(ClientPO ozonClient, String productId, String offerId) throws IOException {
         final CloseableHttpClient httpClient = HttpClients.createDefault();
         final HttpPost httpPost = new HttpPost(GET_PRODUCT_INFO_URL);
         httpPost.addHeader("Client-Id", ozonClient.getClientId());
         httpPost.addHeader("Api-Key", ozonClient.getSecretKey());
         httpPost.addHeader("Content-Type", "application/json");
         httpPost.addHeader("Host", "api-seller.ozon.ru");
         final ImmutableMap<String, Object> params = ImmutableMap.of("product_id", productId, "offer_id", offerId);
         StringEntity stringEntity = new StringEntity(JSONUtil.toJsonStr(params));
         stringEntity.setContentEncoding("UTF-8");
         stringEntity.setContentType("application/json");
         httpPost.setEntity(stringEntity);

         final CloseableHttpResponse response = httpClient.execute(httpPost);
         if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
             log.error("接口请求失败");
         }
         String result = EntityUtils.toString(response.getEntity());
         final JSONObject jsonObject = JSONUtil.parseObj(result).getJSONObject("result");
         return new ProductPO()
                 .setOzonProductId(jsonObject.getStr("id"))
                 .setBarcode(jsonObject.getStr("barcode"))
                 .setName(jsonObject.getStr("name"))
                 .setSku(jsonObject.getStr("sku"))
                 .setOfferId(jsonObject.getStr("offer_id"))
                 .setTypeId(jsonObject.getStr("type_id"))
                 .setCurrencyCode(jsonObject.getStr("currency_code"))
                 .setDescriptionCategoryId(jsonObject.getStr("description_category_id"))
                 .setMarketingPrice(jsonObject.getBigDecimal("marketing_price"))
                 .setOldPrice(jsonObject.getBigDecimal("old_price"))
                 .setPrice(jsonObject.getBigDecimal("price"))
                 .setMinPrice(jsonObject.getBigDecimal("min_price", null))
                 .setImages(jsonObject.getBeanList("images", String.class))
                 .setCreatedAt(jsonObject.getLocalDateTime("created_at", null))
                 .setUpdatedAt(jsonObject.getLocalDateTime("updated_at", null))
                 .setStock(jsonObject.getJSONObject("stocks").getInt("present"))
                 .setVisible(jsonObject.getBool("visible"))
                 .setPrimaryImage(jsonObject.getStr("primary_image"))
                 .setState(jsonObject.getJSONObject("status").getStr("state"))
                 .setClientId(ozonClient.getClientId());
     }
}
